<template>
    <div>
        <el-dialog title="分配权限" :visible.sync="menubarnuVisible" :close-on-click-modal="false"
            :close-on-press-escape="false" @closed="handlerCancel()">
            <el-tree :data="menuTree" show-checkbox node-key="id" ref="tree" :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handlerCancel()">取 消</el-button>
                <el-button type="primary" @click="handlerAssignMenu()">分配权限</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { useInfByIdoApi, addUseApi, editUseApi } from '../../api/UseApi.js'
import { rolesApi, roleByUserApi, assignRoleApi } from '../../api/RoleApi.js'
import { treeMenuApi, currentRoleMenu, assignMenuApi } from '../../api/MenuApi.js'
export default {
    props: ['menubarnuVisible'],
    data() {
        return {

            formLabelWidth: '120px',
            menuTree: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
        };
    },
    mounted() {
        this.loadMenu();

    },
    methods: {
        handlerCancel() {
            this.$emit('closeDialog');

        },
        async handlerAssignMenu() {
            const menuId1 = this.$refs.tree.getCheckedKeys();
            try {
                const data = {
                    roleId: this.roleId,
                    menuIds:menuId1
                }
                const res = await assignMenuApi(data);
                if (res.status === 200) {
                    this.$emit('closeDialog', true);
                } else {
                    this.$message.error(res.msg);
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                this.$message.error('网络错误，请稍后重试');
            }



        },
        async openDialog(roleId) {
            this.roleId = roleId;
            try {
                const res = await currentRoleMenu(roleId);
                if (res.status === 200) {
                    const Keys = res.data.map(item => item.id);
                    this.$refs.tree.setCheckedKeys(Keys)

                } else {
                    this.$message.error(res.msg);
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                this.$message.error('网络错误，请稍后重试');
            }
        },
        async loadMenu() {
            try {
                const res = await treeMenuApi();
                if (res.status === 200) {
                    this.menuTree = res.data;
                } else {
                    this.$message.error(res.msg);
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                this.$message.error('网络错误，请稍后重试');
            }

        },


    }
};

</script>
<style scoped lang="less"></style>